<template>
  <div class='container'>
    <el-card style="margin: 10px">
      <!-- 头部 -->
      <el-row v-if="$route.query.id">
        <span>学科管理</span>
        <i class="el-icon-arrow-right"></i>
        <span>{{$route.query.name}}</span>
        <i class="el-icon-arrow-right"></i>
        <span>目录管理</span>
      <el-divider></el-divider>
      </el-row>
      <!-- form表单 -->
      <el-form label-position="left" inline size="small">
        <el-row type="flex" justify="space-between">
          <el-col :span="12">
            <el-form-item label="目录名称">
              <el-input
                v-model="pageForm.directoryName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="状态">
              <el-select v-model="pageForm.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="hClean">清除</el-button>
              <el-button type="primary" @click="hInquiry">搜索</el-button>
            </el-form-item>
          </el-col>
            <el-form-item>
              <el-button type="text"
               icon="el-icon-back"
              v-if="$route.query.id"
              @click="$router.push('/subjects/list')"
                >返回学科</el-button>
            </el-form-item>
          <el-col :span="4">
            <el-form-item>
              <el-button type="success" @click="hAdd" icon="el-icon-edit"
                >新增目录</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- alert提示 -->
      <el-alert title="" type="info" show-icon> 数据一共{{total}}条 </el-alert>

      <!-- table表格 -->
      <el-table style="margin-top: 15px" :data="tagList">
        <el-table-column
          label="序号"
          type="index"
          :index="pageAdd"
          sortable
          width="100%"
        ></el-table-column>
        <el-table-column label="所属学科" prop="subjectName" width="140%">
        </el-table-column>
        <el-table-column label="目录名称" prop="directoryName" width="140%"></el-table-column>
        <el-table-column label="创建者" prop="username" width="140%"></el-table-column>
        <el-table-column prop="addDate" label="创建时间" width="180">
      <template v-slot="scope">
          <span>{{ dateFormatting(scope.row.addDate) }}</span>
      </template>
      </el-table-column>
        <el-table-column label="面试题数量" prop="totals" width="150%"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            已{{ typeofStatus(scope.row.state) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220%">
          <template v-slot="scope">
            <el-button type="text" @click="hChangeState(scope.row)">{{
              scope.row.state ? "禁用" : "启用"
            }}</el-button>
            <el-button
              type="text"
              @click="hEdit(scope.row)"
              :disabled="!scope.row.state"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="hDel(scope.row)"
              :disabled="!scope.row.state"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- pag分页 -->
      <el-row type="flex" justify="end">
        <el-pagination
          background
          layout="prev,pager,next,sizes,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageForm.pagesize"
          :total="total"
          :page="pageForm.page"
          :current-page.sync="pageForm.page"
        ></el-pagination>
      </el-row>
    </el-card>

    <!-- 弹窗: 新增||编辑 -->
    <el-dialog
      width="400px"
      :visible.sync="showDialog"
      :title="isEdit ? '修改目录' : '新增目录'"
      v-if="showDialog"
    >
    <directorys-add
    :isEdit="isEdit"
    :backFormData = " formData"
    @success = "hsuccess"
    @close="hCleanFormData"
    ref="formAddRef"
    />
    </el-dialog>
  </div>
</template>

<script>
// 导入接口
// import { list as getSubjectList } from '@/api/hmmm/subjects.js'
import { list as directoryList, remove, changeState } from '@/api/hmmm/directorys.js'
import directorysAdd from '@/module-hmmm/components/directorys-add.vue'
import { parseTime } from '@/utils/index.js'
// 导入枚举信息
import { status } from '@/api/hmmm/constants.js'
const sta = status.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})
export default {
  components: {
    directorysAdd
  },
  data () {
    return {
      tagList: [],
      subjectList: [],
      pageForm: {
        directoryName: '',
        page: 1,
        pagesize: 10
      },
      total: 5,
      showDialog: false,

      formData: {}
    }
  },
  created () {
    if (this.$route.query.id) {
      this.pageForm = {
        ...this.pageForm,
        subjectID: this.$route.query.id
      }
    }
    this.loaddirectory()
  },
  methods: {
    // 格式化处理录入时间
    dateFormatting (date) {
      return parseTime(date)
    },
    // 根据id从 sbujectList 内找出学科名字
    getSbjName (id) {
      return this.subjectList.find(item => {
        console.log(item.id, id)
        return item.id === id
      })
    },
    // // 请求学科列表
    // async loadSbjList () {
    //   const res = await getSubjectList()
    //   console.log('学科列表', res)
    //   this.subjectList = res.data.items
    // },
    // 调用子组件方法清空
    hCleanFormData () {
      // console.log(this.$refs.formAddRef.hClean)
      this.showDialog = false
      this.$refs.formAddRef.hClean()
    },
    // 更新成功
    hsuccess () {
      this.pageForm.page = 1
      // 刷新页面
      this.loaddirectory()
      // 关闭弹窗
      this.showDialog = false
    },
    // 删除弹窗提醒
    async hDel (row) {
      this.$confirm('此操作将永久删除该学科,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 做删除
    async doDel (row) {
      try {
        const res = await remove(row)
        // console.log(res)
        if (res.status === 200) {
          this.$message.success('删除成功')
        }
      } catch (error) {
        this.$message.error(error.message)
      }

      // 解决删除后当前页面数据为空bug
      if (this.tagList.length === 1) {
        let page = this.pageForm.page
        page--

        page = Math.max(1, page)
        this.pageForm.page = page
      }
      this.loaddirectory()
    },
    // 更改状态 启用||禁用
    async hChangeState (data) {
      try {
        const letState = data.state ? 0 : 1
        const res = await changeState({
          id: data.id,
          state: letState
        })
        if (res.status === 200) {
          this.$message.success('操作成功')
        }
      } catch (error) {
        this.$message.error(error.message)
      }
      // 更新
      this.loaddirectory()
    },

    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      // 回到第一页
      this.pageForm.page = 1
      this.pageForm.pagesize = val

      // 刷新
      this.loaddirectory(this.pageForm)
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pageForm.page = val

      // 刷新
      this.loaddirectory(this.pageForm)
    },

    // 状态格式转换
    typeofStatus (status) {
      return sta[status]
    },

    // 新增弹窗
    hAdd () {
      this.showDialog = true
      this.isEdit = false
    },

    // 修改弹窗
    hEdit (val) {
      this.showDialog = true
      this.isEdit = true
      // 数据回填
      this.formData = {
        ...val
      }
    },

    // 获取目录列表
    async loaddirectory () {
      if (this.$route.query.id) {
        this.pageForm = {
          ...this.pageForm,
          subjectID: this.$route.query.id
        }
      }
      try {
        const res = await directoryList(this.pageForm)
        console.log('目录列表', res)
        this.tagList = res.data.items
        this.total = res.data.counts
      } catch (error) {}
    },

    // 清空表单
    hClean () {
      this.pageForm = {
        page: 1,
        pagesize: 10,
        title: ''
      }
    },

    // 点击查询
    hInquiry () {
      this.loaddirectory()
    },

    // 连续序号
    pageAdd (index) {
      return (this.pageForm.page - 1) * this.pageForm.pagesize + index + 1
    }
  }
}
</script>

<style scoped>
.container span {
  margin-right: 5px;
  margin-left: 5px;
  font-size: 14px;
}
</style>
